import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:connectivity/connectivity.dart'; // 用作检查连接手否可以使用
import 'dart:convert';

import 'package:sharing/ui/component/filter_input_chip.dart'; //提供可以用来展示搜索历史的
import 'package:shared_preferences/shared_preferences.dart'; // 用来查找搜索历史的
import 'package:sharing/model/search_history.dart';
import 'package:sharing/resources/code_point.dart';
import 'package:sharing/resources/strings.dart';
import 'package:sharing/resources/styles.dart';
import 'package:sharing/resources/font_families.dart';
import 'package:sharing/ui/component/pic_swiper.dart';
import 'package:sharing/ui/component/item_slide_show.dart';
import 'package:sharing/ui/widget/book_info.dart';
import 'package:sharing/mock/books.dart';
import 'package:sharing/model/book.dart';
import 'package:sharing/ui/component/book_with_name.dart';
import 'package:sharing/ui/home/origin_work.dart';
import 'package:sharing/ui/home/recommend_books.dart';
import 'package:sharing/resources/colors.dart';
import 'package:sharing/model/origin_article.dart';
import 'package:sharing/net/net_util.dart';
import 'package:dio/dio.dart';
import 'package:sharing/model/origin_article.dart';
import 'package:sharing/model/simple_user_info.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _connectionStatus = 'Unknown';
  final Connectivity _connectivity = Connectivity();
  StreamSubscription<ConnectivityResult> _connectivitySubscription;
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  ScrollController _scrollController = ScrollController(); // 监听list的滚动事件
  List<Widget> _fixedBodies = [];
  List<OriginArticle> _origins = [];
  int _page = 1;

  // 联动的搜索栏
  final _SearchDelegate _delegate = _SearchDelegate();
  int _lastIntegerSelected;
  List<Book> _books = fetchBooks();

  //List<SearchHistory > historys = [];
  Future<SearchHistory> _historys;

  List<SlideShow> _slideShows = [
    SlideShow(
      src:
//          "https://cn.bing.com/az/hprichbg/rb/GoldfinchSnow_ZH-CN8057863738_1920x1080.jpg",
          "https://img.ffis.me/images/2018/03/25/cc.md.jpg",
      onTap: () {
        print("tap....");
      },
    ),
    SlideShow(
      src:
          "http://static.simpledesktops.com/uploads/desktops/2016/07/16/robo.png",
      onTap: () {
        print("{src}");
      },
    ),
  ];

  @override
  void initState() {
    super.initState();

    initConnectivity();
    _connectivitySubscription =
        _connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
      // 获取当前网络的连接的状态, 如果当前的网络为none
      // 提示用户当前的网络的信息连接不可用
      if (result == ConnectivityResult.none) {
        Scaffold.of(context).showSnackBar(SnackBar(
          content: Text(
            IdString.warningNetNotAvailable,
          ),
          duration: Duration(seconds: 3),
        ));
      }
      // 设置当前网网络的状态信息
      setState(() => _connectionStatus = result.toString());
    });

    // 初始化 historys
    // 从文本中获取初始化的信息, 如果获取失败 ,返回空的搜索的历史
    _historys = _prefs.then((SharedPreferences prefs) {
      if (prefs.getString("search_history") != null) {
        print(
            "prefs.getString('search_history')   ${prefs.getString('search_history')}  ");

        return SearchHistory.fromJson(
            json.decode(prefs.getString("search_history")));
      } else {
        return SearchHistory(items: []);
      }
    });

    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _getMore();
      }
    });

    // fixed body
    _fixedBodies = [
      SizedBox.fromSize(
        size: Size.fromHeight(200),
        // 轮播图组件组装
        child: IndicatorViewPager(pages: _slideShows),
      ),
      SizedBox(
        height: 4.0,
      ),
      Container(
        padding: EdgeInsets.symmetric(horizontal: 8.0),
        height: 36.0,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text(
              "推荐书籍",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: AppStyles.recommendTextStyle,
            ),
            Container(
              // color: Colors.black12,
              child: GestureDetector(
                onTap: () {
                  print("切换一批推荐的书籍");
                },
                child: Text(
                  "切换",
                  style: AppStyles.contextTextStyle,
                ),
              ),
            ),
          ],
        ),
      ),
      RecommendBooks(
        books: fetchBooks(),
      ),
      Container(
        margin: const EdgeInsets.symmetric(horizontal: 4.0),
        color: AppColor.light,
        height: 12.0,
      ),
      OriginWork(
        originArticle: OriginArticle(
          id: 01,
          user: SimpleUserInfo(
              id: 1,
              name: "xuelike",
              signature: '活着就是为了折腾',
              level: '3',
              avatar:
                  "http://static.codeceo.com/images/2015/06/b346575a47ddb61631408f749e6f2139.jpg"),
          coverUrl:
              "http://static.codeceo.com/images/2015/06/b346575a47ddb61631408f749e6f2139.jpg",
          articleUrl: "https://restapitutorial.com/",
          title: "rest api 指北",
          pushDate: DateTime.now().toString(),
          link: 'static/upload/md/test.md',
        ),
      ),
    ];
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<Null> initConnectivity() async {
    String connectionStatus;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      connectionStatus = (await _connectivity.checkConnectivity()).toString();
    } on PlatformException catch (e) {
      print(e.toString());
      connectionStatus = 'Failed to get connectivity.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) {
      return;
    }

    setState(() {
      _connectionStatus = connectionStatus;
    });
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    _scrollController.dispose(); // dispose 的 listview controller
    super.dispose();
  }

  Widget _renderListItem(BuildContext context, int index) {
    int _fix = _fixedBodies.length;

    if (index < _fix) {
      return _fixedBodies[index];
    }

    if (index > _fix && index < _fix + _origins.length) {
      // 这里的下标是 originArticle 的下标
      return _buildOrigin(index - _fix);
    }

    // 正在加载更多的数据
    return _getFetchMore();
  }

  // build OriginWork
  Widget _buildOrigin(int _originIndex) {
    return OriginWork(
      originArticle: _origins[_originIndex],
    );
  }

  Widget _getFetchMore() {
    return Container(
      padding: EdgeInsets.all(16),
      alignment: Alignment.center,
      child: SizedBox(
        width: 24,
        height: 24,
        child: CircularProgressIndicator(
          strokeWidth: 2,
        ),
      ),
    );
  }

  Widget _build(BuildContext context, int index) {
    return BookWithName(
      book: _books[index],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(context),
      body: ListView.builder(
        itemBuilder: _renderListItem,
        itemCount: _fixedBodies.length + _origins.length + 1,
        controller: _scrollController,
      ),
    );
  }

  Widget _buildOriginWork(BuildContext context, int index) {
    int _fixed = _fixedBodies.length;

    return OriginWork(
      originArticle: _origins[index],
    );
  }

//构造app bar
  _buildAppBar(BuildContext context) {
    return AppBar(
      backgroundColor: Colors.white,
      title: Text(
        IdString.homeTitle,
        style: AppStyles.pageTitleTextStyle,
      ),
      elevation: 0.0,
      actions: _buildActions(),
    );
  }

//  构建一个 actions
  List<Widget> _buildActions() {
    return <IconButton>[
      IconButton(
        icon: Icon(
          IconData(IconCode.search, fontFamily: FontFamiles.iconFontFamily),
        ),
        onPressed: () async {
          final int selected = await showSearch<int>(
            context: context,
            delegate: _delegate,
          );

          // 如果选择的不是最后一个
          if (selected != null && selected != _lastIntegerSelected) {
            setState(() {
              _lastIntegerSelected = selected;
            });
          }
        },
      ),
    ];
  }

  // 首页的数据
  void _getData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String auth = prefs.getString("authorization");
    if (auth == null) {
      return;
    }
    NetUtil.getOriginWork(
      (OriginArticle origin) {
        print(origin);
        setState(() {});
      },
      _page,
      Options(headers: {'authorization': auth}),
    );
  }

  // 加载更多的数据
  void _getMore() async {
    _page++;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String auth = prefs.getString("authorization");
    if (auth == null) {
      return;
    }
    NetUtil.getOriginWork(
      (OriginArticle origin) {
        print(origin);
      },
      _page,
      Options(headers: {'authorization': auth}),
    );

    setState(() {});
  }
}

class _SearchDelegate extends SearchDelegate<int> {
  final List<int> _data =
      List<int>.generate(20, (int i) => i).reversed.toList(); // 使用列表生成器
  final List<int> _history = <int>[
    42607,
    42607,
    85604,
    66374,
    44,
    174
  ]; // 搜索历史数据

// 构造最前的 的组件
  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      tooltip: "back ",
      icon: AnimatedIcon(
        icon: AnimatedIcons.menu_arrow,
        progress: transitionAnimation,
      ),
      onPressed: () {
        close(context, null); // 点击关闭
      },
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    final Iterable<int> suggestions = query.isEmpty
        ? _history
        : _data.where((int i) => "$i".startsWith(query));

    return FilterInputChip(
        inputs: suggestions.map<String>((int i) => "$i").toList(),
        query: query,
        onDeleted: () {});
  }

  @override
  Widget buildResults(BuildContext context) {
    final int searched = int.tryParse(query);
    if (searched == null || !_data.contains(searched)) {
      return Center(
        child: Text(
          '"$query"\n is not a valid integer between 0 and 100,000.\nTry again.',
          textAlign: TextAlign.center,
        ),
      );
    }

    return ListView(
      children: <Widget>[],
    );
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return <Widget>[
      IconButton(
        tooltip: 'Clear',
        icon: const Icon(Icons.clear),
        onPressed: () {
          query = ''; // 充值查询值
          showSuggestions(context);
        },
      )
    ];
  }
}

// 构造建议列表
// 要点 : 如果和输入的列表相匹配 加粗和输入列表相同的部分
// 如果和输入列表的不相同, 不加粗
class _SuggestionList extends StatelessWidget {
  const _SuggestionList({this.suggestions, this.query, this.onSelected});

  final List<String> suggestions;
  final String query;
  final ValueChanged<String> onSelected;

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);

    return ListView.builder(
      itemCount: suggestions.length,
      itemBuilder: (BuildContext context, int i) {
        final String suggestion = suggestions[i];

        return ListTile(
          // 如果数据框已经输入的就高亮
          leading: RichText(
            text: TextSpan(
              text: suggestion.substring(0, query.length),
              style: theme.textTheme.subhead
                  .copyWith(fontWeight: FontWeight.bold), // 加粗字体

              // 输入框还没有输入的部分 ,不做加粗处理
              children: <TextSpan>[
                TextSpan(
                  text: suggestion.substring(query.length),
                  style: theme.textTheme.subhead, // 普通字体
                ),
              ],
            ),
          ),
          onTap: () {
            onSelected(suggestion); // 点击选中的文本....
          },
        );
      },
    );
  }
}
